package org.jackysoft.service.impl;

import java.io.File;
import java.util.List;

import org.hibernate.Session;
import org.jackysoft.entity.FileItem;
import org.jackysoft.entity.User;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.DownloadService;
import org.jackysoft.util.FileInfo;
import org.jackysoft.util.IOUtils;
import org.jackysoft.util.OperationType;
import org.jackysoft.util.SpringSecurityUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class DownloadServiceImpl 
extends AbstractStringIdServiceImpl<FileItem>
implements DownloadService {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7690529165031274648L;


	@Override
	public FileInfo download(String id) throws DataAccessException {
		Session sess = getSession();
	    String hql = String.format("select new org.jackysoft.entity.FileItem(r.title,r.diskBase,r.realName,r.fileType) from %s  r where r.id='%s'","ReceivedFileItem",id);
		List list = sess.createQuery(hql).list();
		FileItem fileItem = null;
		
		if(!list.isEmpty()){
			fileItem = (FileItem) list.get(0);
		}else{
			hql = String.format("select new org.jackysoft.entity.FileItem(r.title,r.diskBase,r.realName,r.fileType) from %s r where r.id='%s'","UploadedFileItem",id);
			list = sess.createQuery(hql).list();
		    fileItem = (FileItem) list.get(0);
		    if(fileItem==null){
		    	  return new FileInfo("文件未找到","文件未找到","txt","你要下载的文件未找到".getBytes());
		    }
		    	
		    
		}		
		String realName = String.format("%s:%sfiles%s%s", fileItem.getDiskBase(),File.separator,File.separator,fileItem.getRealName());
				
		byte[] bs = IOUtils.toByteArray(new File(realName));
		User user = SpringSecurityUtils.getCurrentUser();
		String opr = "下载";
		OperationType logType = OperationType.System;
		String details = ("用户 " + user.getLocalName() + "["
				+ user.getUsername() + "] " + opr + id);
		traceLog(logType, opr, details);
		return new FileInfo(fileItem.getTitle(),fileItem.getRealName(),fileItem.getFileType(),bs);
	}

}
